package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.AssertUtils;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningRecordFormDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import com.tianji.learning.utils.LearningRecordDelayTaskHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.tianji.learning.enums.LessonStatus.*;
import static com.tianji.learning.enums.SectionType.VIDEO;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2025-10-22
 */
@Service
@RequiredArgsConstructor
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {
    private final ILearningLessonService lessonService;
    private final CourseClient courseClient;
    private final LearningRecordDelayTaskHandler taskHandler;

    /**
     * 查询当前用户指定课程的学习进度
     *
     * @param courseId
     */
    @Override
    public LearningLessonDTO queryLearningRecordByCourse(Long courseId) {
        // 1、根据userId 和 courseId 查询课表信息
        LearningLesson lesson = lessonService.lambdaQuery()
                .eq(LearningLesson::getUserId, UserContext.getUser())
                .eq(LearningLesson::getCourseId, courseId)
                .one();
        if (ObjectUtil.isEmpty(lesson)) {
            return null;
        }

        // 2、根据 lessonId 查询课表下的 学习记录
        List<LearningRecord> records = this.lambdaQuery().eq(LearningRecord::getLessonId, lesson.getId()).list();

        // 3、封装DTO并返回
        return LearningLessonDTO.of(lesson.getId(), lesson.getLatestSectionId(),
                BeanUtils.copyList(records, LearningRecordDTO.class));
    }

    /**
     * 提交学习记录
     *
     * @param formDTO
     */
    @Override
    @Transactional
    public void subLearningRecord(LearningRecordFormDTO formDTO) {
        // 1、处理学习记录
        boolean firstFinished = formDTO.getSectionType() == VIDEO ? handleVedioRecord(formDTO) : handleExamRecord(formDTO);
        if(!firstFinished && formDTO.getDuration() == -1){
            return;
        }

        // 2、处理课表数据
        handleLearningLesson(formDTO, firstFinished);
    }

    /**
     * 处理考试学习记录
     *
     * @param formDTO
     * @return
     */
    private boolean handleExamRecord(LearningRecordFormDTO formDTO) {
        // 1、将formDTO 转换成 PO
        LearningRecord record = BeanUtils.toBean(formDTO, LearningRecord.class);

        // 2、填充缺失的数据
        record.setUserId(UserContext.getUser());
        record.setFinished(true);
        record.setFinishTime(formDTO.getCommitTime());

        // 3、写入数据库
        boolean result = save(record);
        if (!result) {
            throw new DbException("新增考试学习记录失败");
        }

        // 4、返回是否是第一次学完的标识
        return true;
    }

    /**
     * 处理视频学习记录
     *
     * @param formDTO
     * @return
     */
    private boolean handleVedioRecord(LearningRecordFormDTO formDTO) {
        // 1、查询旧的学习记录
        LearningRecord oldRecord = queryOldRecord(formDTO.getLessonId(),formDTO.getSectionId());

        // 2、判断学习记录是否存在
        if (ObjectUtil.isEmpty(oldRecord)) {
            // 3、如果不存在，新增学习记录
            // 3.1、将formDTO 转换成 PO
            LearningRecord record = BeanUtils.toBean(formDTO, LearningRecord.class);

            // 3.2、填充缺失的数据
            record.setUserId(UserContext.getUser());

            // 3.3、写入数据库
            boolean result = save(record);
            if (!result) {
                throw new DbException("新增视频学习记录失败");
            }
            // 3.4、返回是否是第一次学完的标识
            return false;
        }

        // 4、如果存在，更新学习记录
        // 4.1、判断是否是第一次学完当前小节
        boolean firstFinished = !oldRecord.getFinished() && formDTO.getMoment() << 1 > formDTO.getDuration();

        // 4.2、如果是非第一次学完，将学习记录暂存到redis，并且提交一个延时任务
        if(!firstFinished){
            LearningRecord learningRecord = new LearningRecord();
            learningRecord.setLessonId(formDTO.getLessonId());
            learningRecord.setSectionId(formDTO.getSectionId());
            learningRecord.setId(oldRecord.getId());
            learningRecord.setMoment(formDTO.getMoment());
            learningRecord.setFinished(oldRecord.getFinished());
            taskHandler.addLearningRecordAndDelayCheckTask(learningRecord);
            formDTO.setDuration(-1);
            return false;
        }

        // 4.3、如果是第一次学完，更新学习记录
        boolean updateResult = this.lambdaUpdate()
                .set(LearningRecord::getMoment, formDTO.getMoment())
                .set(LearningRecord::getFinished, firstFinished)
                .set(LearningRecord::getFinishTime, formDTO.getCommitTime())
                .eq(LearningRecord::getId, oldRecord.getId())
                .update();
        if (!updateResult) {
            throw new DbException("更新视频学习记录失败");
        }

        // 4.4、清理redis缓存中的学习记录（目的：保证redis和mysql数据双写一致性）
        taskHandler.cleanLearningRecordCache(formDTO.getLessonId(),formDTO.getSectionId());

        // 5、返回是否是第一次学完的标识
        return firstFinished;
    }

    /**
     * 查询旧的学习记录
     * @param lessonId
     * @param sectionId
     * @return
     */
    private LearningRecord queryOldRecord(Long lessonId, Long sectionId) {
        // 1、先从缓存中查询学习记录
        LearningRecord oldRecord = taskHandler.readLearningRecordFromCache(lessonId,sectionId);

        // 2、判断缓存中是否存在数据，如果存在，直接返回
        if(ObjectUtil.isNotEmpty(oldRecord)){
            return oldRecord;
        }

        // 3、如果不存在，则查询数据库，并将结果放入缓存
        // select * from learning_record where lesson_id = ? and section_id = ?
        oldRecord = this.lambdaQuery()
                .eq(LearningRecord::getLessonId, lessonId)
                .eq(LearningRecord::getSectionId, sectionId)
                .one();
        if(ObjectUtil.isEmpty(oldRecord)){
            return null;
        }

        taskHandler.writeLearningRecordToCache(oldRecord);

        // 4、返回数据
        return oldRecord;
    }

    /**
     * 处理课表数据
     *
     * @param formDTO
     * @param firstFinished
     */
    private void handleLearningLesson(LearningRecordFormDTO formDTO, boolean firstFinished) {
        // 1、查询课表数据（已学习小节数）
        LearningLesson lesson = this.lessonService.getById(formDTO.getLessonId());
        AssertUtils.isNotNull(lesson, "查询课表数据失败");

        // 2、查询全部小节是否已学完标识
        boolean allLearnd = false;
        if (firstFinished) {
            // 2.1、查询课程数据（总小节数）
            CourseFullInfoDTO courseInfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
            AssertUtils.isNotNull(courseInfo, "查询课程数据失败");

            // 2.2、比较（已完成小节数 + 1 >= 课程总小节数）
            allLearnd = lesson.getLearnedSections() + 1 >= courseInfo.getSectionNum();
        }

        // 3、更新课表数据
        boolean updateResult = this.lessonService.lambdaUpdate()
                .set(LearningLesson::getLatestSectionId, formDTO.getSectionId())
                .set(LearningLesson::getLatestLearnTime, formDTO.getCommitTime())
                .set(firstFinished, LearningLesson::getLearnedSections, lesson.getLearnedSections() + 1)
                //.setSql(firstFinished,"learned_sections = learned_sections + 1")
                .set(allLearnd, LearningLesson::getStatus, FINISHED)
                .set(lesson.getStatus() == NOT_BEGIN, LearningLesson::getStatus, LEARNING)
                .eq(LearningLesson::getId, formDTO.getLessonId())
                .update();
        if (!updateResult) {
            throw new DbException("更新课表记录失败");
        }
    }

}
